package com.jxb.demo.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;

/**
 * @desc netty服务端handler
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private static Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);

    /**
     * @desc 连接成功处理
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("连接成功，channelId：{}",ctx.channel().id());

        ctx.channel().writeAndFlush("client 连接成功");
    }

    /**
     * @desc 关闭连接处理
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("连接关闭，channelId：{}",ctx.channel().id());
    }

    /**
     * @desc 读取消息处理
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        List<Msg> msgList = (List<Msg>) msg;
        logger.info("msg:{}",msgList);
        Msg respMsg = new Msg();
        respMsg.setMsgId("resp-1");
        respMsg.setMsgInfo("欢迎你发送信息过来");
        respMsg.setUserName("system");
        respMsg.setMsgTime(System.currentTimeMillis());
        ctx.channel().writeAndFlush(respMsg);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }

    /**
     * @desc 异常处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //super.exceptionCaught(ctx, cause);
        logger.error("ERROR:{}",cause.getMessage());
        ctx.close();
    }


}
